package cn.fx.service.impl;

import cn.fx.UserMovieDto;
import cn.fx.domain.MovieTicket;
import cn.fx.exception.enums.GlobalEnum;
import cn.fx.mapper.MovieTicketMapper;
import cn.fx.result.JsonResult;
import cn.fx.service.IMovieTicketService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Fx
 * @since 2022-09-01
 */
@Service
public class MovieTicketServiceImpl extends ServiceImpl<MovieTicketMapper, MovieTicket> implements IMovieTicketService {

    @Autowired
    private MovieTicketMapper movieTicketMapper;

    /**
     * @Description: 购买电影票
     * @Author: Fx
     * @Date: 2022/9/1
     * @param userId 用户id
     * @param movieId 电影id
     * @return cn.fx.result.JsonResult
     */

    @Override
    public JsonResult buy(Long userId, Long movieId) {
        // 查询电影票库存，库存不足提示用户
        MovieTicket movieTicket = selectById(movieId);
        if (movieTicket.getStock() == 0){
            return JsonResult.error(GlobalEnum.MOVIE_ISNULL_ERROR);
        }
        // 查询中间表
        UserMovieDto userMovieDto = movieTicketMapper.selectMovieIdByUserId(userId, movieId);
        if (userMovieDto == null){
            // 中间表数据为空，用户没有买，新增
            UserMovieDto userMovie = new UserMovieDto(userId, movieId, 1);
            movieTicketMapper.insertUserMovie(userMovie);
        }else {
            // 用户买过，修改状态
            userMovieDto.setStatus(0);
            movieTicketMapper.updateUseerMovie(userMovieDto);
        }
        // 扣减库存
        movieTicket.setStock(movieTicket.getStock() - 1);
        updateById(movieTicket);
        return JsonResult.success(movieTicket.getPrice());
    }

    /**
     * @Description: 观看电影
     * @Author: Fx
     * @Date: 2022/9/1
     * @param userId 用户id
     * @param movieId 电影id
     * @return cn.fx.result.JsonResult
     */

    @Override
    public JsonResult expiration(Long userId, Long movieId) {

        // 查询用户要观看的电影票
        MovieTicket movieTicket = selectById(movieId);
        // 电影结束时间要大于当前时间
        if (movieTicket.getEndTime().getTime() < new Date().getTime()){
            return JsonResult.error(GlobalEnum.MOVIE_EXPIRED_ERROR);
        }

        UserMovieDto userMovieDto = movieTicketMapper.selectMovieIdByUserId(userId, movieId);
        if (userMovieDto == null){
            return JsonResult.error(GlobalEnum.MOVIE_PUT_ERROR);
        }else {
            if (userMovieDto.getStatus() < 1){
                return JsonResult.error(GlobalEnum.MOVIE_PUT_ERROR);
            }
        }
        // 如果有说明用户买过，那么就修改
        userMovieDto.setStatus(0);
        movieTicketMapper.updateUseerMovie(userMovieDto);

        return JsonResult.success(GlobalEnum.OK);
    }
}
